package com.mazaiting.web.advice;

import com.alibaba.fastjson.JSON;
import com.mazaiting.common.core.domain.result.Result;
import com.mazaiting.web.domain.ErrorRequestBean;
import com.mazaiting.web.domain.SingleResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Map;
import java.util.Objects;

/**
 * 统一返回
 * 拦截Controller方法的返回值，统一处理返回值/响应体，一般用来统一返回格式，加解密，签名等等
 * 1. 全局异常处理
 * 2. 全局数据绑定
 * 3. 全局数据预处理
 *
 * @author mazaiting
 * @create_time 2022/4/17 09:50
 */
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(@NonNull MethodParameter returnType,
                            @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  @NonNull MethodParameter returnType,
                                  @NonNull MediaType selectedContentType,
                                  @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @NonNull ServerHttpRequest request,
                                  @NonNull ServerHttpResponse response) {

        // 上层包装过的数据 或 字符串 直接返回
        if (body instanceof Result<?> || body instanceof String) {
            return body;
        }
        // data 只返回字符串
        if (body instanceof SingleResult singleResult) {
            return Result.success(singleResult.getData());
        }
        // map 集合数据, 校验是不是失败的数据
        if (body instanceof Map<?,?>) {
            // 处理 404 等的异常
            ErrorRequestBean errorRequestBean = JSON.parseObject(JSON.toJSONString(body), ErrorRequestBean.class);
            if (Objects.nonNull(errorRequestBean) && !ObjectUtils.isEmpty(errorRequestBean.getStatus())) {
//                return Result.failed(ResultCode.SERVLET_ERROR_NOT_FOUND_REQUEST);
                return Result.failed(errorRequestBean.getError());
            }
        }
        return Result.success(body);
    }
}
